#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>

#define COMMAND_SIZE 1024
char* g_argv[128];
int g_argc=0;

const char* get_user()
{
  const char* e = getenv("USER");
  return e;
}

const char* get_host()
{
  const char* e = getenv("HOSTNAME");
  return e;
}

const char* get_pwd()
{
  const char* e = getenv("PWD");
  return e;
}

std::string dir_name(const char* pwd)
{
  std::string dir = pwd;
  if(dir == "/") return "/";
  auto pos = dir.rfind("/");
  return dir.substr(pos+1); 
}
void make_command_prompt(char pro[],int size)
{
  snprintf(pro,size,"[%s@%s %s]#",get_user(),get_host(),dir_name(get_pwd()).c_str());
}

void print_command_prompt()
{
  char pro[COMMAND_SIZE];
  make_command_prompt(pro,COMMAND_SIZE);
  printf("%s",pro);
  fflush(stdout);
}

bool get_command_line(char* out,int size)
{
  char* c = fgets(out,size,stdin);
  if(c==NULL) return false;

  if(strlen(out)==0) return false;
  out[strlen(out)-1] = 0; // 清理\n
  if(strlen(out) == 0) return false;
  return true;

}

bool command_parse(char* command_line)
{
  g_argc=0;
  g_argv[g_argc++]= strtok(command_line," ");
  while((bool)(g_argv[g_argc++]=strtok(nullptr," ")));
  g_argc--;  
  return true;
}
void print_command_line()
{
  for(int i=0;g_argv[i];i++)
  {
    printf("[%d]->%s\n",i,g_argv[i]);
  }
  printf("size=%d\n",g_argc);
}
int execute()
{

    //执行命令
    pid_t id = fork();
    if(id == 0)
    {
      //child
      execvp(g_argv[0],g_argv);
      exit(1);
      
    }
    //father
    pid_t rid = waitpid(id,nullptr,0);
    (void)rid;
    return 0;

}
int main()
{
  while(true)
  {
    //输入命令行提示符
    print_command_prompt();
    //获取用户输入的命令
    char command_line[COMMAND_SIZE];
    if(!get_command_line(command_line,sizeof(command_line)))
    {
      continue;  
    }
    //命令行分析
    command_parse(command_line);
    //print_command_line();
    //执行命令
    execute();
  }

  return 0;
  
  
}
